//
//  ZSUserAccountTableViewController.m
//  ZhuShou
//
//  Created by Dejun Liu on 15/11/2.
//  Copyright © 2015年 jw. All rights reserved.
//

#import "ZSUserAccountTableViewController.h"
#import "ZSOneTableViewCell.h"
#import "JWAnimationManager.h"
#import "ZSBlindingMoblieViewController.h"
#import "ZSLoginViewController.h"
#import "ZSRevisePasswordViewController.h"

typedef NS_ENUM(NSUInteger, AccountSetting) {
    AccountSettingPortrait,
    AccountSettingName,
    AccountSettingEmail,
    AccountSettingMobile,
    AccountSettingPassword,
    AccountSettingExit
};
@interface ZSUserAccountTableViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate, ZSBlindingMoblieViewControllerDelegate>

@property (nonatomic,strong) NSArray *list;
@property (nonatomic,strong) JWAnimationManager *am;
@property (weak, nonatomic) IBOutlet UIButton *moblieBlindBtn;
@property (weak, nonatomic) IBOutlet UITextField *moblieTextField;
@property (weak, nonatomic) IBOutlet UITextField *testTextField;

@end

@implementation ZSUserAccountTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setHidesBottomBarWhenPushed:YES];

    self.title = @"账户信息";
    self.list = @[@{
                      @"title":@"头像",
                      @"value":@"menu_icon_arm",
                      @"type":@(AccountSettingPortrait)
                      },
                  @{
                      @"title":@"名称",
                      @"value":@"cheneylew",
                      @"type":@(AccountSettingName)
                      },
                  @{
                      @"title":@"账户邮箱",
                      @"value":@"cheneylew@163.com",
                      @"type":@(AccountSettingEmail)
                      },
                  @{
                      @"title":@"手机绑定",
                      @"value":@"15221584917",
                      @"type":@(AccountSettingMobile)
                      },
                  @{
                      @"title":@"修改账号密码",
                      @"value":@"",
                      @"type":@(AccountSettingPassword)
                      },
                  @{
                      @"title":@"退出当前账号",
                      @"value":@"",
                      @"type":@(AccountSettingExit)
                      }
                  ];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZSOneTableViewCell" bundle:nil] forCellReuseIdentifier:@"Cell"];
    
    if (!self.am) {
        self.am = [JWAnimationManager new];
        self.am.isPopViewAdaptWindowWidth = YES;
        }
    
    //配置inputView颜色
    self.inputView.layer.cornerRadius = 10.0f;
    self.inputView.clipsToBounds = YES;
    self.moblieView.layer.cornerRadius = 10.0f;
    self.moblieView.clipsToBounds = YES;
    self.moblieBlindBtn.layer.borderColor = [UIColor grayColor].CGColor;
    self.moblieBlindBtn.layer.borderWidth = 1;
    self.moblieTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.testTextField.keyboardType = UIKeyboardTypeNumberPad;

//    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestData:)];
//    self.tableView.header = header;
//    
//    MJRefreshAutoStateFooter *footer = [MJRefreshAutoStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestData:)];
//    self.tableView.footer = footer;
//    
//    [self.tableView.header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"Cell";
    ZSOneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    NSDictionary *dic = [self.list objectAtIndex:indexPath.row];
    cell.df_titleTextLabel.text = [dic objectForKey:@"title"];
    cell.df_detailTextLabel.text = [dic objectForKey:@"value"];
    AccountSetting type = [[dic objectForKey:@"type"]integerValue];
    if (type == AccountSettingPortrait) {
        cell.df_rightImageView.hidden = NO;
        cell.df_rightImageView.image = [UIImage imageNamed:[dic objectForKey:@"value"]];
        cell.df_detailTextLabel.hidden = YES;
    }else
    {
        cell.df_detailTextLabel.hidden = NO;
        cell.df_detailTextLabel.text = [dic objectForKey:@"value"];
        cell.df_rightImageView.hidden = YES;
        
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dic = [self.list objectAtIndex:indexPath.row];
    AccountSetting type = [[dic objectForKey:@"type"]integerValue];

    if (AccountSettingPortrait == type) {
        
        [self.am popView:self.popView startLocation:JWAnimationLocation_Bottom endLocation:JWAnimationLocation_Bottom tapMaskBlock:^{
            [self.am removeViewFromPopView:self.popView toLocation:JWAnimationLocation_Bottom complationBlock:nil];
        }];
    }  else if(AccountSettingName == type){
    
        [self.am popView:self.inputView startLocation:JWAnimationLocation_Bottom endLocation:JWAnimationLocation_Center tapMaskBlock:^{
            [self.inputView_textField resignFirstResponder];
            [self.am removeViewFromPopView:self.inputView toLocation:JWAnimationLocation_Bottom complationBlock:nil];
        }];
        [self.inputView_textField becomeFirstResponder];
        
    } else if (AccountSettingMobile == type){
        
        ZSBlindingMoblieViewController *blindMoblieViewController = [[ZSBlindingMoblieViewController alloc] initWithMoblieNumber:dic[@"value"]];
        blindMoblieViewController.delegate = self;
        [self.navigationController pushViewController:blindMoblieViewController animated:YES];
    } else if (AccountSettingExit == type){
    
    [self br_alertViewConfirmWithTitle:@" " content:@"确定是否退出当前用户!" operationIndex:^(NSInteger clickedIndex) {
        if (1 == clickedIndex) {
            
            // 跳转回登录界面
            ZSLoginViewController *login = [[ZSLoginViewController alloc] init];
            UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:login];
            [self presentViewController:navi animated:YES completion:nil];
        }
        }];
    } else if (AccountSettingPassword == type){
        [self br_pushViewControllerWithClassName:@"ZSRevisePasswordViewController"];
    }
    
}

#pragma mark RequestData

- (void)requestData:(MJRefreshHeader *) commponent
{
    [self.tableView.header endRefreshing];
    [self.tableView.footer endRefreshing];
    [self.tableView.footer noticeNoMoreData];
}

#pragma mark Button Actions

- (IBAction)pickImageFromAlbum:(id)sender {
    [self.am removeViewFromPopView:self.popView toLocation:JWAnimationLocation_Bottom complationBlock:^{
        UIImagePickerControllerSourceType sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
            
        }
        
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.navigationBar.translucent = NO;
        picker.delegate = self;
        picker.allowsEditing=YES;
        picker.sourceType=sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }];
    
}

- (IBAction)pickImageFromCamera:(id)sender {
    [self.am removeViewFromPopView:self.popView toLocation:JWAnimationLocation_Bottom complationBlock:^{
        UIImagePickerControllerSourceType sourceType=UIImagePickerControllerSourceTypeCamera;
        
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
            
        }
        
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing=YES;
        picker.sourceType=sourceType;
        picker.navigationBar.translucent = NO;
        [self presentViewController:picker animated:YES completion:nil];
    }];
}

- (IBAction)cancelPickImage:(id)sender {
    [self.am removeViewFromPopView:self.popView toLocation:JWAnimationLocation_Bottom complationBlock:nil];
}

- (IBAction)cancelNicknameInput:(id)sender {
    [self.am removeViewFromPopView:self.inputView toLocation:JWAnimationLocation_Bottom complationBlock:nil];
}

#pragma mark 修改昵称
- (IBAction)confirmNicknameInput:(id)sender {
    
    [self.am removeViewFromPopView:self.inputView toLocation:JWAnimationLocation_Bottom complationBlock:nil];
//    NSString *tempStr = [JWUserManger sharedInstance].serverNickname;//将原来的昵称保留
    //修改昵称不能为空,不能包含空格，20>长度>2
    NSRange textRange = [self.inputView_textField.text rangeOfString:@" "];//字符串是否有空格
    if ([[self.inputView_textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        [self br_AutoDisappearWithText:@"昵称不能为空"];
    }
    else if (textRange.location != NSNotFound)
    {
        [self br_AutoDisappearWithText:@"昵称不能包含空格"];
    }
    else if (self.inputView_textField.text.length < 1 || self.inputView_textField.text.length > 8)
    {
        [self br_AutoDisappearWithText:@"昵称长度不符合"];
    }
    else
    {
#warning todo

        // 上传昵称成功失败处理
//        [JWUserManger sharedInstance].serverNickname = self.inputView_textField.text;//获得新的昵称
//        [[JWUserManger sharedInstance] reloadDataWithMBAnimation:YES];
//        [[JWUserManger sharedInstance] uploadUserInfoIsSuccess:^(returnType type) {
//            [[JWUserManger sharedInstance] reloadDataWithMBAnimation:NO];
//            if (type == returnUpDataSuccess) {
//                [self br_AutoDisappearWithText:@"修改昵称成功"];
//                [self setData];
//            }
//            else if (type == returnUpDataFailureWithTokenNosame)
//            {
//                [self br_AutoDisappearWithText:@"该用户已登录，请再次登录"];
//                
//                [self.navigationController popViewControllerAnimated:YES];
//                if ([self.delegate respondsToSelector:@selector(JWUCSettingViewControllerUserOnline)]) {
//                    [self.delegate JWUCSettingViewControllerUserOnline];
//                }
//            }
//            else if (type == returnFailureWithServer)
//            {
//                [self displayHintAutoDisappear:[JWUserManger sharedInstance].errorStr];
//                //失败则将原来的昵称显示
//                [JWUserManger sharedInstance].serverNickname = tempStr;
//            }
//            
//        }];
        
    }
    
}
#pragma mark 相机选取照片Picker处理
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage * image=[info objectForKey:UIImagePickerControllerEditedImage];
    [self performSelector:@selector(selectPic:) withObject:image afterDelay:0.1];
}

- (void)selectPic:(UIImage*)image
{
    
    //保留原图片，如果没有成功则显示原图片
//    UIImage *oldImage = [JWUserManger sharedInstance].userNewtworkImage;
    
    
    __weak ZSUserAccountTableViewController *weakSelf = self;
#warning todo  上传图片

//    [[JWUserManger sharedInstance]uploadPortrait:[image dataPNG] completion:^(id responseData, NSError *error) {
//        
//        if (responseData) {
//            NSDictionary *dic = responseData;
//            if ([dic numberForKey:@"flag"].intValue == 1) {
//                
//                
//                NSString *url = [dic stringForKey:@"ico"];
//                
//                [JWUserManger sharedInstance].customIconStr = url;
//                
//                [[JWUserManger sharedInstance] uploadUserInfoIsSuccess:^(returnType type) {
//                    
//                    [[JWUserManger sharedInstance] reloadDataWithMBAnimation:NO];
//                    if (type == returnUpDataSuccess) {
//                        
//                        //                        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
//                        //成功后才去下载，刷新头像
//                        [JWUserManger sharedInstance].userNetworkPortrait = url;
//                        [weakSelf performAfter:0.5 block:^{
//                            [weakSelf.view makeToast:@"头像修改成功！" duration:1 position:CSToastPositionCenter];
//                        }];
//                        [self setData];
//                    }
//                    else if (type == returnUpDataFailureWithTokenNosame)
//                    {
//                        //                        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
//                        //用户已登录就不去下载
//                        [self displayHintAutoDisappear:@"该用户已登录，请再次登录"];
//                        [self.navigationController popViewControllerAnimated:YES];
//                        if ([self.delegate respondsToSelector:@selector(JWUCSettingViewControllerUserOnline)]) {
//                            [self.delegate JWUCSettingViewControllerUserOnline];
//                        }
//                    }
//                    else if (type == returnFailureWithServer)
//                    {
//                        //                        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
//                        [JWUserManger sharedInstance].userNewtworkImage = oldImage;
//                        [self displayHintAutoDisappear:[JWUserManger sharedInstance].errorStr];
//                        
//                    }
//                }];
//            }
//        }
//        else
//        {
//            //            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
//            [[JWUserManger sharedInstance] reloadDataWithMBAnimation:NO];
//            [JWUserManger sharedInstance].userNewtworkImage = oldImage;//将原图片显示
//            [weakSelf performAfter:0.5 block:^{
//                [self displayHintAutoDisappear:@"头像修改失败，请检查网络是否连接"];
//            }];
//        }
//    }];
    
    
}
- (IBAction)moblieMessageSend:(id)sender {
    [self.moblieBlindBtn setTitle:@"正在发送..." forState:UIControlStateNormal];
    // 获取验证码请求发送，获得验证码成功后，显示再次发送
#warning todo
    
}

- (IBAction)moblieBlindingCannel:(id)sender {
//    [self.am removeViewFromPopView:self.moblieView toLocation:JWAnimationLocation_Bottom complationBlock:nil];
}

- (IBAction)moblieBlindingClick:(id)sender {
    [self.am removeViewFromPopView:self.moblieView toLocation:JWAnimationLocation_Bottom complationBlock:nil];

    NSRange textRange = [self.moblieTextField.text rangeOfString:@" "];//字符串是否有空格
    if ([[self.moblieTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        [self br_AutoDisappearWithText:@"手机号码不能为空"];
    }
    else if (textRange.location != NSNotFound)
    {
        [self br_AutoDisappearWithText:@"手机号码不能包含空格"];
    }
    else if (self.testTextField.text.length < 1)
    {
        [self br_AutoDisappearWithText:@"验证码不能为空"];
    }
    else
    {
#warning todo

        // 上传手机号和验证码，上传成功，刷新该行
    }
}

#pragma mark -ZSBlindingMoblieViewControllerDelegate- 
- (void)ZSBlindingMoblieViewControllerClickBlind{
    [self.am popView:self.moblieView startLocation:JWAnimationLocation_Bottom endLocation:JWAnimationLocation_Center tapMaskBlock:^{
        [self.moblieTextField resignFirstResponder];
        [self.am removeViewFromPopView:self.moblieView toLocation:JWAnimationLocation_Bottom complationBlock:nil];
    }];
    [self.moblieTextField becomeFirstResponder];
}

@end
